//
//  UserAccount.swift
//  CXCWeibo
//
//  Created by cxc on 15/6/25.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    var access_token:String
    var expires_in:NSTimeInterval
    /**
    *  创建过期日期
    */
    var expiresDate:NSDate
    var uid:String
    var name:String?
    var avatar_large:String?
    
    init(dict:[String: AnyObject]) {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        uid = dict["uid"] as! String
    }
    
    override var description:String{
        let properties = ["access_token","expires_in","uid","expiresDate","name","avatar_large"]
        return "\(self.dictionaryWithValuesForKeys(properties))"
    }
    
    /// 记载用户信息
    func loadUserInfo(finished:(account:UserAccount?,error:NSError?)->()){
        
        let params = ["access_token":access_token,"uid":uid]
        
        NetworkTools.sharedNetworkTools().GET("2/users/show.json", parameters: params, success: { (_, JSON) -> Void in
            let dict = JSON as! [String:AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            self.saveAccount()
            finished(account: self, error: nil)
            
            }) { (_, error) -> Void in
                finished(account: nil, error: error)
        }
        
    }
    // MARK:  - 保存和加载文件
    static let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    
    func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)

        print(UserAccount.accountPath)
    }
    
    class func loadAccount() -> UserAccount? {
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount{
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
        }
        return nil
    }
    
    // MARK: - NSCoding 归档接档使用的 key 保持一致即可
    ///  解档方法，aDecoder 解码器，将保存在磁盘的二进制文件转换成 对象，和反序列化很像
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    ///  归档，aCoder 编码器，将对象转换成二进制数据保存到磁盘，和序列化很像
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
}
